<?php

/**
 * Created by PhpStorm.
 * User: bob
 * Date: 21/9/25
 * Time: 上午10:37
 */

namespace App\Api\Admin\Controllers;

use App\Api\Account\Models\CommitTag;
use App\Api\Admin\Models\Banner;
use App\Api\Admin\Models\Community;
use App\Api\Admin\Models\Site;
use App\Api\Admin\Models\Subway;
use App\Api\Admin\Models\SubwaySite;
use App\Api\Web\Models\Bbs;
use App\Api\Web\Services\BbsService;
use App\Http\Controllers\Controller;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Qiniu\Auth;

class ConfigController extends Controller
{
    /**
     * 地铁线路列表
     * @param Request $request
     * @return array
     */
    public function subwayIndex(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $subways = Subway::orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();;
        return $this->formatOutput($subways);
    }

    /**
     * 创建或者修改地铁线路
     * @param Request $request
     * @return array
     */
    public function subwayCreateOrUpdate(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        $name = data_get($params, 'name', '');
        $province = data_get($params, 'province', '');
        $city = data_get($params, 'city', '');
        $district = data_get($params, 'district', '');
        $cun = data_get($params, 'cun', '');
        $line = data_get($params, 'line', '');
        $siteCount = data_get($params, 'site_count', '');
        $startAt = data_get($params, 'start_at', '');
        $endAt = data_get($params, 'end_at', '');
        $discription = data_get($params, 'discription', '');
        $siteId = data_get($params, 'site_id', []);

        if (empty($id)) {
            $r = Subway::create([
                'name' => $name,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'cun' => $cun,
                'line' => $line,
                'site_count' => $siteCount,
                'start_at' => $startAt,
                'end_at' => $endAt,
                'discription' => $discription,
            ]);
            $id = data_get($r, 'id');
            if (!empty($siteId) && is_array($siteId)) {
                foreach ($siteId as $v) {
                    $isExist = SubwaySite::where('subway_id', '=', $id)
                        ->where('site_id', '=', $v)
                        ->first();
                    if (empty($isExist)) {
                        SubwaySite::create([
                            'subway_id' => $id,
                            'site_id' => $v,
                        ]);
                    }
                }
            }

        } else {
            $updates = [];
            empty($name) ? : $updates['name'] = $name;
            empty($city) ? : $updates['city'] = $city;
            empty($district) ? : $updates['district'] = $district;
            empty($line) ? : $updates['line'] = $line;
            empty($siteCount) ? : $updates['site_count'] = $siteCount;
            empty($startAt) ? : $updates['start_at'] = $startAt;
            empty($endAt) ? : $updates['end_at'] = $endAt;
            empty($discription) ? : $updates['discription'] = $discription;
            $r = Subway::find($id)->update($updates);
            if (!empty($siteId) && is_array($siteId)) {
                foreach ($siteId as $v) {
                    $isExist = SubwaySite::where('subway_id', '=', $id)
                        ->where('site_id', '=', $v)
                        ->first();
                    if (empty($isExist)) {
                        SubwaySite::create([
                            'subway_id' => $id,
                            'site_id' => $v,
                        ]);
                    }
                }
            }

        }

        return $this->formatOutput($r);
    }

    public function subwayDelete(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        Subway::find($id)->delete();
        return $this->formatOutput('success');
    }

    /**
     * 地铁站点列表
     * @param Request $request
     * @return array
     */
    public function siteIndex(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $subwayId = data_get($params, 'subway_id', '');
        $sites = Site::orderBy('id', 'desc')
            ->leftJoin('subway', 'subway.id', '=', 'site.subway_id')
            ->select('site.*', 'subway.name as subway_name');
        if (!empty($subwayId)) {
            $sites = $sites->where('site.subway_id', '=', $subwayId);
        }
        $sites = $sites
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        return $this->formatOutput($sites);
    }

    /**
     * 创建或者修改地铁站点
     * @param Request $request
     * @return array
     */
    public function siteCreateOrUpdate(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        $name = data_get($params, 'name', '');
        $nearby = data_get($params, 'nearby', '');
        $longitude = data_get($params, 'longitude', '');
        $latitude = data_get($params, 'latitude', '');
        $subwayId = data_get($params, 'subway_id', '');
        $no = data_get($params, 'no', '');

        if (empty($id)) {
            $r = Site::create([
                'name' => $name,
                'nearby' => $nearby,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'subway_id' => $subwayId,
                'no' => $no,
            ]);
        } else {
            $updates = [];
            empty($name) ? : $updates['name'] = $name;
            empty($nearby) ? : $updates['nearby'] = $nearby;
            empty($longitude) ? : $updates['longitude'] = $longitude;
            empty($latitude) ? : $updates['latitude'] = $latitude;
            empty($subwayId) ? : $updates['subway_id'] = $subwayId;
            empty($no) ? : $updates['no'] = $no;
            $r = Site::find($id)->update($updates);
        }

        return $this->formatOutput($r);
    }

    public function siteDelete(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        Site::find($id)->delete();
        return $this->formatOutput('success');
    }

    /**
     * 小区列表
     * @param Request $request
     * @return array
     */
    public function communityIndex(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);
        $name = data_get($params, 'name', '');
        $sites = Community::orderBy('id', 'desc')
            ->leftJoin('subway as s1', 's1.id', '=', 'community.near_subway1')
            ->leftJoin('subway as s2', 's2.id', '=', 'community.near_subway2')
            ->leftJoin('site as si1', 'si1.id', '=', 'community.near_site1')
            ->leftJoin('site as si2', 'si2.id', '=', 'community.near_site2')
            ->select('community.*', 's1.name as near_subway1_name', 's2.name as near_subway2_name', 'si1.name as near_site1_name',
                'si2.name as near_site2_name');
        if (!empty($name)) {
//            $sites = $sites->where('community.name', 'like', "%$name%");
            $sites = $sites->where(function ($query) use ($name) {
                $query->where('s1.name', 'like', "%$name%")
                    ->orwhere('s2.name', 'like', "%$name%")
                    ->orwhere('si1.name', 'like', "%$name%")
                    ->orwhere('si2.name', 'like', "%$name%")
                    ->orwhere('community.name', 'like', "%$name%")
                    ->orwhere('community.near_buildings', 'like', "%$name%")
                    ->orwhere('community.near_bus_stop', 'like', "%$name%")
                    ->orwhere('community.near_company', 'like', "%$name%")
                    ->orwhere('community.business', 'like', "%$name%")
                    ->orwhere('community.near_area', 'like', "%$name%");
            });
        }
        $sites = $sites
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        foreach ($sites['data'] as $k => $v) {
            $sites['data'][$k]['keywords'] = explode(',', data_get($v, 'keywords', ''));
            $sites['data'][$k]['banner'] = json_decode(data_get($v, 'banner', ''));
        }
        return $this->formatOutput($sites);
    }

    /**
     * 创建或者修改小区
     * @param Request $request
     * @return array
     */
    public function communityCreateOrUpdate(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        $name = data_get($params, 'name', '');
        if (empty($id) && empty($name)) {
            throw new \LogicException('缺少必要参数', 100);
        }
        $subwayId = data_get($params, 'subway_id', '');
        $discription = data_get($params, 'discription', '');
        $shortName = data_get($params, 'short_name', '');
        $province = data_get($params, 'province', '');
        $city = data_get($params, 'city', '');
        $district = data_get($params, 'district', '');
        $cun = data_get($params, 'cun', '');
        $subwaySiteId = data_get($params, 'subway_site_id', '');
        $nearBuildings = data_get($params, 'near_buildings', '');
        $nearBusStop = data_get($params, 'near_bus_stop', '');
        $nearCompany = data_get($params, 'near_company', '');
        $nearArea = data_get($params, 'near_area', '');
        $longitude = data_get($params, 'longitude', '');
        $latitude = data_get($params, 'latitude', '');
        $years = data_get($params, 'years', '');
        $type = data_get($params, 'type', '');
        $developer = data_get($params, 'developers', '');
        $business = data_get($params, 'business', '');
        $tenement = data_get($params, 'tenement', '');
        $logo = data_get($params, 'logo', '');
        $banners = data_get($params, 'banner', []);
        if (is_array($banners) && !empty($banners)) {
            foreach ($banners as $k => $banner) {
                $banners[$k] = $banner;
            }
        } else {
            $banners = [];
        }

        $banner = json_encode($banners);
        $keywords = implode(',', data_get($params, 'keywords', []));
        $near_subway1 = data_get($params, 'near_subway1', '');
        $near_site1 = data_get($params, 'near_site1', '');
        $near_subway2 = data_get($params, 'near_subway2', '');
        $near_site2 = data_get($params, 'near_site2', '');

        if (empty($id)) {
            $r = Community::create([
                'name' =>$name ,
                'subway_id' =>$subwayId ,
                'discription' =>$discription ,
                'short_name' =>$shortName ,
                'province' =>$province ,
                'city' =>$city ,
                'district' =>$district ,
                'cun' =>$cun ,
                'subway_site_id' =>$subwaySiteId ,
                'near_buildings' =>$nearBuildings ,
                'near_bus_stop' =>$nearBusStop ,
                'near_company' => $nearCompany ,
                'near_area' =>$nearArea ,
                'longitude' =>$longitude ,
                'latitude' =>$latitude ,
                'years' =>$years ,
                'type' =>$type ,
                'developers' =>$developer ,
                'business' =>$business ,
                'tenement' =>$tenement ,
                'logo' =>$logo ,
                'banner' =>$banner ,
                'keywords' =>$keywords ,
                'near_site1' =>$near_site1 ,
                'near_subway1' =>$near_subway1 ,
                'near_site2' =>$near_site2 ,
                'near_subway2' =>$near_subway2 ,
            ]);
        } else {
            $updates = [];
            empty($name) ? : $updates['name'] = $name ;
            empty($subwayId) ? : $updates['subway_id'] = $subwayId ;
            empty($discription) ? : $updates['discription'] = $discription ;
            empty($shortName) ? : $updates['short_name'] = $shortName ;
            empty($province) ? : $updates['province'] = $province ;
            empty($city) ? : $updates['city'] = $city ;
            empty($district) ? : $updates['district'] = $district ;
            empty($subwaySiteId) ? : $updates['subway_site_id'] = $subwaySiteId ;
            empty($nearBuildings) ? : $updates['near_buildings'] = $nearBuildings ;
            empty($nearBusStop) ? : $updates['near_bus_stop'] = $nearBusStop ;
            empty($nearCompany) ? : $updates['near_company'] = $nearCompany ;
            empty($nearArea) ? : $updates['near_area'] = $nearArea ;
            empty($longitude) ? : $updates['longitude'] = $longitude ;
            empty($latitude) ? : $updates['latitude'] = $latitude ;
            empty($years) ? : $updates['years'] = $years ;
            empty($type) ? : $updates['type'] = $type ;
            empty($developer) ? : $updates['developers'] = $developer ;
            empty($business) ? : $updates['business'] = $business ;
            empty($tenement) ? : $updates['tenement'] = $tenement ;
            empty($logo) ? : $updates['logo'] = $logo ;
            empty($banner) ? : $updates['banner'] = $banner ;
            empty($keywords) ? : $updates['keywords'] = $keywords ;
            empty($near_site1) ? : $updates['near_site1'] = $near_site1 ;
            empty($near_subway1) ? : $updates['near_subway1'] = $near_subway1 ;
            empty($near_site2) ? : $updates['near_site2'] = $near_site2 ;
            empty($near_subway2) ? : $updates['near_subway2'] = $near_subway2 ;
            $r = Community::find($id)->update($updates);
        }

        return $this->formatOutput($r);
    }

    public function communityDelete(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        Community::find($id)->delete();
        return $this->formatOutput('success');
    }


    public function bannerIndex(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);


        $r = Banner::where('status', '>', -900)
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();

        return $this->formatOutput($r);
    }

    public function bannerUpdateOrCreate(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');

        $name = data_get($params, 'name', '');
        $img = data_get($params, 'img', '');
        $url = data_get($params, 'url', '');
        $status = data_get($params, 'status', 200);

        if (empty($id)) {
            Banner::create([
                'name' => $name,
                'img' => $img,
                'url' => $url,
                'status' => $status
            ]);
        } else {
            $updates = [];
            empty($name) ? : $updates['name'] = $name;
            empty($img) ? : $updates['img'] = $img;
            empty($url) ? : $updates['url'] = $url;
            empty($status) ? : $updates['status'] = $status;
            if (!empty($updates)) {
                Banner::find($id)
                    ->update($updates);
            }
        }

        return $this->formatOutput('success');
    }

    public function bannerDelete(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }

        $banner = Banner::find($id)
            ->update([
                'status' => -900,
            ]);
//        info('delete banner', [$banner]);
        return $this->formatOutput('success');
    }

    public function bbsRelease(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $r = BbsService::release($params, 'admin', $user->id);
        return $this->formatOutput($r);
    }

    public function bbsOne(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');

        $r = Bbs::find($id);
        if (!empty($r)) {
            $user = User::find(data_get($r, 'user_id'));
            $r->user_name = data_get($user, 'name', '未知');
            $r->user_head_img = data_get($user, 'head_img', '未知');
            \DB::table('house_wanted')->where('id', $id)->increment('pv');
        }
        \DB::table('bbs')->where('id', $id)->increment('pv');
        return $this->formatOutput($r);
    }

    public function bbsIndex(Request $request)
    {
        $params = $request->all();
        $pageSize = data_get($params, 'page_size', 20);
        $page = data_get($params, 'page', 1);


        $r = Bbs::where('status', ">=", 200)
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        return $this->formatOutput($r);
    }


    public function bbsDelete(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }

        Bbs::where('id', '=', $id)
            ->update([
                'status' => '-900'
            ]);

        return $this->formatOutput('success');
    }
    public function commitTagCreate(Request $request)
    {
        $params = $request->all();

        $tag = data_get($params, 'tag', '');
        $id = data_get($params, 'id', '');
        if (empty($tag)) {
            throw new \LogicException('缺少必要参数', 100);
        }

        if (!empty($id)) {
            CommitTag::find($id)
                ->update([
                    'tag' => $tag
                ]);
        } else {
            $r = CommitTag::create([
                'tag' => $tag,
            ]);
        }


        return $this->formatOutput('success');
    }

    public function commitTagDelete(Request $request)
    {
        $params = $request->all();
        $id = data_get($params, 'id', '');
        if (empty($id)) {
            throw new \LogicException('缺少必要参数', 100);
        }


        CommitTag::find($id)->delete();

        return $this->formatOutput('success');
    }
}
